<template>
  <div>
      <s-table :search-params="searchForm" :COLUMNS="columns" :async-fc="page" ref="table">
          <template #tableHeader>
            <t-space>
              <t-button @click="insert">新增信息</t-button>
              <t-upload 
                  :headers="authHeaders" 
                  :action="importUrl" 
                  allow-upload-duplicate-file
                  @success="uploadSuccess" 
                  :file-list-display="null" 
                  accept=".xlsx , .xls"
                  >
                <t-button theme="warning">导入数据</t-button>
              </t-upload>
              <t-button @click="exportExcel">导出数据</t-button>
            </t-space>
          </template>
      </s-table>
      <t-dialog v-model:visible="modalOpen" width="80%" @confirm="onModalSubmit">
          <t-form ref="submitFormRef" :rules="FORM_RULES" :data="submitForm">
            <t-row style="width: 100%" :gutter="[10,24]">
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.title')" name="title">
                  <t-input v-model="submitForm.title" :placeholder="t('pages.food.titlePlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.typeId')" name="typeId">
                  <t-select clearable v-model="submitForm.typeId" :options="typeOptions" :placeholder="t('pages.food.typeIdPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.nutrient')" name="nutrient">
                  <t-input v-model="submitForm.nutrient" :placeholder="t('pages.food.nutrientPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.heat')" name="heat">
                  <t-input-number  theme="column" style="width:100%" v-model="submitForm.heat" :placeholder="t('pages.food.heatPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.protein')" name="protein">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.protein" :placeholder="t('pages.food.proteinPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.fat')" name="fat">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.fat" :placeholder="t('pages.food.fatPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.carbonWater')" name="carbonWater">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.carbonWater" :placeholder="t('pages.food.carbonWaterPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.dietaryFiber')" name="dietaryFiber">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.dietaryFiber" :placeholder="t('pages.food.dietaryFiberPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.vitaminA')" name="vitaminA">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.vitaminA" :placeholder="t('pages.food.vitaminAPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.vitaminC')" name="vitaminC">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.vitaminC" :placeholder="t('pages.food.vitaminCPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.vitaminE')" name="vitaminE">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.vitaminE" :placeholder="t('pages.food.vitaminEPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.carrot')" name="carrot">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.carrot" :placeholder="t('pages.food.carrotPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.vitaminB1')" name="vitaminB1">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.vitaminB1" :placeholder="t('pages.food.vitaminB1Placeholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.vitaminB2')" name="vitaminB2">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.vitaminB2" :placeholder="t('pages.food.vitaminB2Placeholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.niacin')" name="niacin">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.niacin" :placeholder="t('pages.food.niacinPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.cholesterol')" name="cholesterol">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.cholesterol" :placeholder="t('pages.food.cholesterolPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.magnesium')" name="magnesium">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.magnesium" :placeholder="t('pages.food.magnesiumPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.iron')" name="iron">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.iron" :placeholder="t('pages.food.ironPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.calcium')" name="calcium">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.calcium" :placeholder="t('pages.food.calciumPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.zinc')" name="zinc">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.zinc" :placeholder="t('pages.food.zincPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.copper')" name="copper">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.copper" :placeholder="t('pages.food.copperPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.manganese')" name="manganese">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.manganese" :placeholder="t('pages.food.manganesePlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.potassium')" name="potassium">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.potassium" :placeholder="t('pages.food.potassiumPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.phosphorus')" name="phosphorus">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.phosphorus" :placeholder="t('pages.food.phosphorusPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.sodium')" name="sodium">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.sodium" :placeholder="t('pages.food.sodiumPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.selenium')" name="selenium">
                  <t-input-number theme="column" style="width:100%" v-model="submitForm.selenium" :placeholder="t('pages.food.seleniumPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">    
              <t-form-item :label="t('pages.food.remarks')" name="remarks">
                  <t-textarea v-model="submitForm.remarks" :placeholder="t('pages.food.remarksPlaceholder')"/>
              </t-form-item>
                </t-col>
                <t-col :span="3">
                    <t-form-item :label="t('pages.food.imageUrls')" name="imageUrls">
                    <s-upload v-model:value="submitForm.imageUrls" type="image" value-type="string" :limit="2" :tip="t('pages.food.imageUrlsPlaceholder')" />
              </t-form-item>
                </t-col>
            </t-row>    
          </t-form>
      </t-dialog>
  </div>
</template>
<script setup lang="ts">
/*****                                          引用部分开始                                          *****/
import { onMounted, ref } from "vue";
import { t } from "@/locales";
import STable from '@/components/s-table/index.vue';
import SUpload from '@/components/s-upload/index.vue';
import SImageView from '@/components/ImageView/index.vue';
import { TableInstanceFunctions } from "@/components/s-table/type";
import { searchParams,COLUMNS,FORM_RULES } from './props/Food'
import { page, updateApi, insertApi, deleteById } from "@/api/food";
import { FormInstanceFunctions, Link, Space, MessagePlugin, DialogPlugin } from "tdesign-vue-next";
import { getOptions } from "@/api/foodType";
import { fileView } from "@/api/upload";
import { useUserStore } from "@/store";
import { download } from "@/utils/request/file";

/*****                                          引用部分结束                                          *****/


/*****                                          属性定义部分开始                                          *****/
const submitForm = ref({
  id:null,
  title:'',
  typeId:'',
  imageUrls:'',
  nutrient:'',
  heat:'',
  protein:'',
  fat:'',
  carbonWater:'',
  dietaryFiber:'',
  vitaminA:'',
  vitaminC:'',
  vitaminE:'',
  carrot:'',
  vitaminB1:'',
  vitaminB2:'',
  niacin:'',
  cholesterol:'',
  magnesium:'',
  iron:'',
  calcium:'',
  zinc:'',
  copper:'',
  manganese:'',
  potassium:'',
  phosphorus:'',
  sodium:'',
  selenium:'',
  remarks:'',
  //添加所用到的字段
});
const searchForm = ref(searchParams);
const typeOptions = ref([]);
const modalOpen = ref(false);
const submitFormRef = ref<FormInstanceFunctions>(null);
const table = ref<TableInstanceFunctions>(null);
const user = useUserStore();
const authHeaders = { [user.tokenHead]: user.token };
const importUrl = `${import.meta.env.VITE_API_URL}/food/import`;
const exportExcel = async () => {
  download('/food/export',{pageNo: 1, pageSize: 10,params: {}},'foods.xls');
};
/*****                                          属性定义部分结束                                          *****/


const columns = ref(COLUMNS.concat([
{
  align: 'left',
  fixed: 'right',
  width: 120,
  colKey: 'op',
  title: t('components.commonTable.operation'),
  cell: (h, slot:{row:any}) => h(Space, {}, [
      h(Link, {
          theme: 'primary',
          onClick: () => {
              submitForm.value = slot.row;
              modalOpen.value = true;
          }
      }, '修改'),
      h(Link, {
          theme: 'danger',
          onClick: () => {
              const confirmDialog = DialogPlugin.confirm({
                  header: `提示`,
                  body: `删除后，标记为${slot.row.id}的所有信息将被清空，且无法恢复`,
                  confirmBtn: {
                      content: '提交',
                      theme: 'primary',
                      loading: false,
                  },
                  theme: 'warning',
                  onConfirm: async () => {
                      confirmDialog.update({ confirmBtn: { content: '提交中', loading: true } });
                      await deleteById(slot.row.id);
                      MessagePlugin.success('删除成功！');
                      table.value.onSearch();
                      confirmDialog.update({ confirmBtn: { content: '提交', loading: false } });
                      confirmDialog.hide();
                  },
              })
          }
      }, '删除'),
  ])
}]

));


/*****                                          页面方法开始                                          *****/
const insert = () => {
  modalOpen.value = true;
  submitForm.value = {
  //配置默认值，但是也要把用到字段写出来
  id:null,
  title:'',
  typeId:'',
  imageUrls:'',
  nutrient:'',
  heat:'',
  protein:'',
  fat:'',
  carbonWater:'',
  dietaryFiber:'',
  vitaminA:'',
  vitaminC:'',
  vitaminE:'',
  carrot:'',
  vitaminB1:'',
  vitaminB2:'',
  niacin:'',
  cholesterol:'',
  magnesium:'',
  iron:'',
  calcium:'',
  zinc:'',
  copper:'',
  manganese:'',
  potassium:'',
  phosphorus:'',
  sodium:'',
  selenium:'',
  remarks:'',
  };
  // 重置表单实例
  if (submitFormRef.value) {
     submitFormRef.value.reset();
}
}

/**
* 提交表单
*/
const onModalSubmit = async () => {
  const valid = await submitFormRef.value.validate();
  if (valid === true) {
      if (submitForm.value.id) {
          await updateApi(submitForm.value);
      } else {
          await insertApi(submitForm.value);
      }
      MessagePlugin.success('操作成功！');
      modalOpen.value = false;
      table.value.onSearch();
  }
}

onMounted( async () => {
  // 获取表格数据
  const data = await getOptions(null);
  typeOptions.value = data;
  searchForm.value = searchParams.concat([{
    label:t('pages.food.typeId'),
    key:'typeId',
    valueType:'select',
    options: data
  }]);
  columns.value.splice(1,0,{
        title: t('pages.food.typeId'),
        ellipsis: true,
        fixed: 'left',
        align: 'center',
        colKey: 'typeId',
        cell:(h,{row}) => {
            return data.find((i:any) => i.value == row.typeId).label;
        },
});
});

const uploadSuccess = () => {
  MessagePlugin.success("导入成功！");
   table.value.onSearch();
};

/*****                                          页面方法结束                                          *****/
</script>